//
// Created by 11510 on 2024/6/12.
//

#include "Logger.h"
#include <log4cpp/FileAppender.hh>
#include <log4cpp/Priority.hh>
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/FileAppender.hh>
#include <iostream>
using namespace log4cpp;
using std::cout;
using std::endl;

/**
 * NOTICE!!!
 * 易错点：定义放在头文件会报错重定义
 */
Logger *Logger::_pInstance = nullptr;

/**
 * 无参构造
 */
Logger::Logger():_cat(Category::getRoot().getInstance("root")) {
    PatternLayout *ptn1 = new PatternLayout();
    ptn1->setConversionPattern("%d %c [%p] %m%n");

    PatternLayout *ptn2 = new PatternLayout();
    ptn2->setConversionPattern("%d %c [%p] %m%n");

    OstreamAppender *pos = new OstreamAppender("console", &cout);
    pos->setLayout(ptn1);

    FileAppender *file = new FileAppender("file", "server.log");

    _cat.setPriority(Priority::DEBUG);
    _cat.addAppender(pos);
    _cat.addAppender(file);

    cout << "log construct" << endl;
}

/**
 * 析构函数
 */
Logger::~Logger(){
    Category::shutdown();
    cout << "~ log" << endl;
}

Logger* Logger::getInstance() {
    if(nullptr == _pInstance){
        _pInstance = new Logger();
    }
    return _pInstance;
}

void Logger::destroy() {
    if(_pInstance) {
        delete _pInstance;
        _pInstance = nullptr;
    }
}


void Logger::warn(const char *msg) {
    _cat.warn(msg);
}


void Logger::error(const char *msg) {
    _cat.error(msg);
}


void Logger::debug(const char *msg) {
    _cat.debug(msg);
}

void Logger::info(const char *msg) {
    _cat.info(msg);
}

